package com.atguigui.leetcode1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 2451.差值数组不同的字符串
 * Project: leetcode
 * Package: com.atguigui.leetcode1
 * Version: 1.0
 * <p>
 * Created by WJX on 2023/5/25 14:15
 */
public class P2451OddStringDifference {
    public static void main(String[] args) {
        Solution solution = new P2451OddStringDifference().new Solution();
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public String oddString(String[] words) {
            int[] diff0 = get(words[0]);
            int[] diff1 = get(words[1]);
            //如果0和1相等，则比较0和之后的
            if (Arrays.equals(diff0, diff1)) {
                for (int i = 2; i < words.length; i++) {
                    //有一个不相等则返回那个不同的
                    if (!Arrays.equals(diff0, get(words[i]))) {
                        return words[i];
                    }
                }
            }
            //如果0和1不相等，则比较0和2，2必定和0或1相等
            return Arrays.equals(diff0, get(words[2])) ? words[1] : words[0];
        }

        public int[] get(String word) {
            int[] diff = new int[word.length() - 1];
            for (int i = 0; i + 1 < word.length(); i++) {
                diff[i] = word.charAt(i + 1) - word.charAt(i);
            }
            return diff;
        }


        public String oddString2(String[] words) {
            var d = new HashMap<String, List<String>>();
            for (var s : words) {
                var m = s.length();
                var cs = new char[m - 1];
                for (var i = 0; i < m - 1; ++i) {
                    cs[i] = (char) (s.charAt(i + 1) - s.charAt(i));
                }
                var t = String.valueOf(cs);
                d.computeIfAbsent(t, word -> new ArrayList<>()).add(s);
            }

            for (var value : d.values()) {
                if (value.size() == 1) return value.get(0);
            }
            return "";
        }


    }
}
